package com.github.cyf.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author chenyifan
 * @create 2025-05-29 16:34
 */
@Configuration
public class ThreadPoolConfig {

    @Bean("mdcThreadPoolTaskExecutor")
    public ThreadPoolTaskExecutor mdcThreadPoolTaskExecutor() {
        MdcThreadPoolTaskExecutor executor = new MdcThreadPoolTaskExecutor();
        // 核心线程池大小
        executor.setCorePoolSize(5);
        // 最大可创建的线程数
        executor.setMaxPoolSize(20);
        // 等待队列最大长度
        executor.setQueueCapacity(200);
        // 线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(100);
        // 线程池对拒绝任务(无线程可用)的处理策略
        // 当线程池和队列已满，新提交的任务将由调用者所在的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程名前缀
        executor.setThreadNamePrefix("async-exec-");
        // 初始化
        executor.initialize();
        return executor;
    }

    @Bean("threadPoolTaskExecutor")
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 核心线程池大小
        executor.setCorePoolSize(5);
        // 最大可创建的线程数
        executor.setMaxPoolSize(20);
        // 等待队列最大长度
        executor.setQueueCapacity(200);
        // 线程池维护线程所允许的空闲时间
        executor.setKeepAliveSeconds(100);
        // 线程池对拒绝任务(无线程可用)的处理策略
        // 当线程池和队列已满，新提交的任务将由调用者所在的线程执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 线程名前缀
        executor.setThreadNamePrefix("async-exec-");
        // 初始化
        executor.initialize();
        return executor;
    }
}
